import BaseTank from "./BaseTank"
import { Dir, Globals } from "./Global"
import MapLayer from "./MapLayer";
import AudioMgr from "./AudioMgr";
import Game from "./Game"

const {ccclass, property} = cc._decorator;

@ccclass
export default class EnemyTank extends BaseTank {
    readonly _maxDistance: number = 100;
    _curDistance: number = 0;
    game: Game;
    _isInvincible: boolean;
    _isPropTank: boolean;
    _movingAnimation: string;

    init(pos: cc.Vec3, propTank: boolean) {
        this.mapLayer = cc.find("/Canvas/GameLayer/MapLayer").getComponent(MapLayer);
        this._curDistance = 0;
        this.game = cc.find("/Game").getComponent(Game);
        this._isInvincible = true;

        this.randomTank();

        this.node.position = pos;
        this.isEnemy = true;
        this._isPropTank = propTank;
        this.getComponent(cc.Animation).play("star");

        // 控制方向
        this.schedule(() => {
            if (this._curDistance >= this._maxDistance) {
                this._curDistance = 0;
                this.changeDir();
            }
        }, 0.1);

        // 控制发射子弹
        this.schedule(() => {
            if (!this.autoMoving) {
                return;
            }
            if (100 * Math.random() <= Globals.ENEMY_ATTACK_WEIGHT) {
                this.shoot();
            }
        }, 0.5);
    }

    // TODO 后续考虑设置各个坦克的随机权重
    randomTank() {
        let instance_level = this.game.level;
        if (instance_level < 10) {
            // 前10关只会出现1-4级坦克
            this.level = Math.ceil(Math.random() * 4);
        } else {
            this.level = Math.ceil(Math.random() * 6);
        }

        // 坦克血量根据等级划分
        if (this.level <= 3) {
            this.blood = 1;
        } else if (this.level > 4) {
            this.blood = 3;
        } else {
            this.blood = 2;
        }
    }

    shoot() {
        // 可能处于道具暂停中
        if (this.mapLayer.isPropStopping) {
            return;
        }
        this.mapLayer.createBullet(this.dir, this.node.position, this.level, this);
    }

    disBlood() {
        if (this._isInvincible) {
            return;
        }

        if (this.blood <= 0) {
            return;
        }

        if (--this.blood == 0) {
            this.onEnemyDestroyed();
        } else {
            cc.find("/Game/AudioMgr").getComponent(AudioMgr).playAudio("bin", false);
            this._playMovingAnimation();
        }
    }

    protected update(dt: number): void {
        // 可能处于道具暂停中
        if (this.mapLayer.isPropStopping) {
            return;
        }
        if (!this.autoMoving) return;
        // 不同坦克速度不一样，关卡等级越高，坦克速度也越快
        let speed = 25;
        if (this.level == 2) {
            speed = 40;
        } else if (this.level > 3) {
            speed = 15;
        }
        // 关卡加成速度
        speed += this.game.level;
        if (speed > 50) {
            speed = 50;
        }
        let realStep = speed * dt;
        this._autoMoving(realStep);        
    }

    // star动画播放完后执行
    afterStarAnimationCompleted() {
        this._isInvincible = false;
        this.autoMoving = true;
        this.setDir(Dir.DOWN);
        this._playMovingAnimation();
    }

    _playMovingAnimation() {
        this._movingAnimation = "emoving" + this.level;
        if (this._isPropTank) {
            let tmp_level = this.level;
            if (tmp_level > 4) {
                tmp_level = 4;
            }
            this._movingAnimation = "pemoving" + tmp_level;
        }
        this.getComponent(cc.Animation).play(this._movingAnimation);
    }

    _playMovingAnimationStop() {
        this.getComponent(cc.Animation).stop(this._movingAnimation);
    }

    setDir(dir: Dir) {
        if (this.dir == dir) {
            return;
        }

        let oldPosition = this.node.position;

        this._adjustPosition();

        // 如果产生碰撞，则回到之前的位置
        if (this._isCollisionWithMap() || this._isCollisionWithBlock() || this._isCollisionWithTank()) {
            this.node.position = oldPosition;
 
            // 移动了最大距离会改变方向
            this._curDistance = this._maxDistance;
        }

        this.dir = dir;
        this.node.angle = -90 * this.dir;

        // 产生贴图
        this._playMovingAnimation();
    }

    changeDir() {
        let choice = Math.random();
        if (choice < 0.4) {
            this.setDir(Dir.DOWN);
        } else if (choice < 0.6) {
            this.setDir(Dir.LEFT);
        } else if (choice < 0.8) {
            this.setDir(Dir.UP);
        } else {
            this.setDir(Dir.RIGHT);
        }
        this._playMovingAnimation();
    }
	
    onEnemyDestroyed(donotPlayAduio: boolean=false) {
        if (!donotPlayAduio) {
            cc.find("/Game/AudioMgr").getComponent(AudioMgr).playAudio("tank_bomb", false);
        }

        this.autoMoving = false;
        this.unscheduleAllCallbacks();
        this._playMovingAnimationStop();
        this.getComponent(cc.Animation).play("blast");
        
        // 出现道具
        if (this._isPropTank) {
            this.mapLayer.spawnProp();
        }

        this.scheduleOnce(()=>{
            this.mapLayer.destoryEnemy(this.node);
        }, 0.5);
    }

    _autoMoving(realStep: number) {
        // 记录移动前的位置
        let oldPosition = this.node.position;
 
        switch (this.dir) {
            case Dir.LEFT:
                this.node.x -= realStep;
                break;
            case Dir.UP:
                this.node.y += realStep;
                break;
            case Dir.RIGHT:
                this.node.x += realStep;
                break;
            case Dir.DOWN:
                this.node.y -= realStep;
                break;
            default:
                break;
        }
 
        this._curDistance += realStep;
 
        // 如果产生碰撞，则回到之前的位置
        if (this._isCollisionWithMap() || this._isCollisionWithBlock() || this._isCollisionWithTank()) {
            this.node.position = oldPosition;
 
            // 移动了最大距离会改变方向
            this._curDistance = this._maxDistance;
        }
    }
}
